package org.example.nt.v1;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.PemUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.SM2;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslProvider;
import org.example.nt.NettyServerHandler;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        socketChannel.pipeline().addLast(createSslHandler(initSSLContext(), false));
        // 编解码
//        socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
//        socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        socketChannel.pipeline().addLast(new NettyServerHandler());
    }

    private ChannelHandler createSslHandler(SslContext sslContext, boolean needsClientAuth) {
        return sslContext.newHandler(ByteBufAllocator.DEFAULT);
    }

    private SslContext initSSLContext() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
        PrivateKey key = null;
        X509Certificate[] certs = null;
        SslProvider provider = SslProvider.OPENSSL;
        return SslContextBuilder.forServer(key, certs)
                .sslProvider(provider)
                .build();
    }

    public static void main(String[] args) {
        SM2 sm2 = SmUtil.sm2();
        PrivateKey privateKey = sm2.getPrivateKey();
        PublicKey publicKey = sm2.getPublicKey();
        PemUtil.writePemObject("EC PRIVATE KEY", privateKey.getEncoded(), FileUtil.getOutputStream("sm2-private.pem"));
        PemUtil.writePemObject("EC PUBLIC KEY", publicKey.getEncoded(), FileUtil.getOutputStream("sm2-public.pem"));
        PrivateKey privateKey1 = PemUtil.readPemPrivateKey(FileUtil.getInputStream("sm2-private.pem"));
        PublicKey publicKey1 = PemUtil.readPemPublicKey(FileUtil.getInputStream("sm2-public.pem"));
        System.out.println(Base64.encode(privateKey1.getEncoded()).equals(Base64.encode(privateKey.getEncoded())));
        System.out.println(Base64.encode(publicKey1.getEncoded()).equals(Base64.encode(publicKey.getEncoded())));
    }
}
